$(function () {
    // 图片上传
    let $uploadBtn = $("#upload-news-thumbnail");
    let $imageUrlInput = $("#news-thumbnail-url");
    $uploadBtn.change(function () {
        let file = this.files[0];
        let imageForm = new FormData();
        imageForm.append("image_file", file);

        $.ajax({
            url: "/x-admin/news/image/upload/",
            type: "POST",
            data: imageForm,
            contentType: false,
            processData: false,
        }).done(function (res) {
            if(res.errno==="0"){
                fAlert.alertSuccessToast("上传成功");
                let imageUrl = res["data"]["image_url"]
                $imageUrlInput.val(imageUrl);
            }
            else{
                fAlert.alertErrorToast(res.errmsg);
            }
        }).fail(function(err){
            fAlert.alertErrorToast("网络出现问题，请刷新重试");
        })
    });
    
    // 内容上传
    let $pubBtn = $("#btn-pub-news");
    $pubBtn.click(function () {
        let title = $("#news-title").val();
        let desc = $("#news-desc").val();
        let image_url = $("#news-thumbnail-url").val();
        let cate = $("#news-category").val();
        let content = $("#content").val();
        let id = $(this).data("news-id");

        if(title.length===0){
            fAlert.alertErrorToast("标题不能为空");
            return;
        }
        if(desc.length===0){
            fAlert.alertErrorToast("文章简介不能为空");
            return;
        }
        if(desc.length>=120){
            fAlert.alertErrorToast("文章简介不能大于120个字符");
            return;
        }
        if(image_url.length===0){
            fAlert.alertErrorToast("必须设置缩略图");
            return;
        }
        if(cate.length===0){
            fAlert.alertErrorToast("请选择文章分类");
            return;
        }
        if(content.length===0){
            fAlert.alertErrorToast("文章内容不能为空");
            return;
        }

        let data = {
            title: title,
            digest: desc,
            tag: cate,
            content: content,
            image_url: image_url,
        };
        let url = id? "/x-admin/news/edit/" + id + "/": "/x-admin/news/pub/";
        $.ajax({
            url: url,
            type: id?"PUT": "POST",
            data: JSON.stringify(data),
            contentType:"application/json;charset=utf-8",
            dataType: "JSON",
        }).done(function (res) {
            if(res.errno==="0"){
                fAlert.alertSuccessToast(res.errmsg);
                setTimeout(()=>{
                    window.location.href = "/x-admin/news/";
                }, 1000);
            }
            else{
                fAlert.alertErrorToast(res.errmsg);
            }
        }).fail(function () {
            fAlert.alertErrorToast("网络出现问题，请重试");
        })

    });
})